package com.crpc.common;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class CThreadFactory implements ThreadFactory {

    private String threadNamePrefix;
    private AtomicInteger count = new AtomicInteger();
    private boolean daemon;

    private CThreadFactory() {

    }

    public static ThreadFactory create(String threadPrefix) {
        return create(threadPrefix,false);
    }

    public static ThreadFactory create(String threadPrefix,boolean daemon) {
        CThreadFactory threadFactory = new CThreadFactory();
        threadFactory.threadNamePrefix = threadPrefix;
        threadFactory.daemon = daemon;
        return threadFactory;
    }

    @Override
    public Thread newThread(Runnable r) {
        int currentIndex = count.getAndIncrement();
        if(currentIndex >= Integer.MAX_VALUE) {
            count.compareAndSet(currentIndex,0);
        }

        String threadName = this.threadNamePrefix + "-" + currentIndex;
        Thread thread = new Thread(r,threadName);
        thread.setDaemon(daemon);
        return thread;
    }
}
